using MultiAgentsShared;
using static MultiAgentsClient.Manager.ProjectManager;
using static MultiAgentsClient.Presentation.ChatRoomListModel;

namespace MultiAgentsClient.Presentation;

public partial record CreateProjectPopupModel
{
    private readonly IEventBus eventBus;

    public IState<string> NewProjectName => State.Value(this, () => "");
    public IState<string> NewProjectSetting => State.Value(this, () => "");
    public IState<bool> IsPopupOpen => State.Value(this, () => false);

    public CreateProjectPopupModel()
    {
        eventBus = EventBus.Instance;

        eventBus.Subscribe<CreateProjectClickCommand>(async cmd => { await CreateProjectClickCommandEvent(); });
        eventBus.Subscribe<CreateProjectCompleteCommand>(async cmd => { await CreateProjectCompletedEvent(); });
    }

    public async ValueTask CreateProject()
    {
        string? inputStr = await NewProjectName;
        string? projectSettingsStr = await NewProjectSetting ?? "";
        if (inputStr == null || inputStr == "")
        {
            return;
        }

        eventBus.Publish(new CreateProjectCommand(inputStr, projectSettingsStr));
    }

    public async ValueTask Close()
    {
        await IsPopupOpen.SetAsync(false);
    }

    private async ValueTask CreateProjectClickCommandEvent()
    {
        await IsPopupOpen.SetAsync(true);
    }

    private async ValueTask CreateProjectCompletedEvent()
    {
        await NewProjectName.Set(string.Empty, default);
        await NewProjectSetting.Set(string.Empty, default);
        await IsPopupOpen.SetAsync(false);
    }
}
